package o2o.web.actions.tip;

import o2o.config.dao.UserDaoSql;
import com.jinyou.utils.common.*;
import o2o.cache.tip.TipInfoMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.tip.TipInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.common.FileUploadInfo;
import o2o.dao.VO.tip.TipInfoVO;
import o2o.web.actions.user.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import o2o.system.data.SYS_CONFIG_PATH;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

//提示信息
@Controller
public class TipInfoAction {


    //按类别获取提示信息
    @RequestMapping(method = RequestMethod.POST, value = "/tip/info/list")
    @ResponseBody
    public String type_list(Integer tipType, Integer page, Integer size) {
        List<TipInfo> list = TipInfoMemory.getInstance().listOfType(tipType);
        if (ValidateUtil.isAbsList(list)) {
            if (null != page && null != size) {
                //需要分页
                JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
                if (null != pageList && null != pageList.list) {
                    List<TipInfoVO> voList = conventTOVOList((List<TipInfo>) pageList.list);
                    if (ValidateUtil.isAbsList(voList)) {
                        return AjaxResult.successResult(pageList.totalCount, voList.size(), voList);
                    }
                }
            } else {
                List<TipInfoVO> voList = conventTOVOList(list);
                if (ValidateUtil.isAbsList(voList)) {
                    return AjaxResult.successResult(voList.size(), voList);
                }
            }
        }

        return AjaxResult.successResult(0, 0, null);
    }

    //----------------------------------------管理
    //新增
    @RequestMapping(method = RequestMethod.POST, value = "/admin/tip/info/add")
    @ResponseBody
    public String shop_label_add(String token, TipInfo info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (null == info) {
            return AjaxResult.errorResult("信息不完整，请填写完整");
        }

        if (ValidateUtil.isNull(info.getName())) {
            return AjaxResult.errorResult("请输入名称");
        }

        if (null == info.getTipType()) {
            return AjaxResult.errorResult("类别不能为空");
        }


        long time = DateUtils.getCurrTime();
        info.setCreateTime(time);
        info.setDelFlag(0);
        info.setCreateUser(user.getUsername());

        //存入数据库
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.TIP_INFO, info);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("新增失败，请稍后再试");
        }

        //存入缓存
        TipInfoMemory.getInstance().add(time);

        return AjaxResult.successResult();
    }

    //修改
    @RequestMapping(method = RequestMethod.POST, value = "/admin/tip/info/modify")
    @ResponseBody
    public String shop_label_modify(String token, TipInfo info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (null == info) {
            return AjaxResult.errorResult("信息不完整，请填写完整");
        }

        if (ValidateUtil.isNotID(info.getId())) {
            return AjaxResult.errorResult("请选择要修改的");
        }

        if (null == info.getTipType()) {
            return AjaxResult.errorResult("类别不能为空");
        }

        TipInfo tipInfo = TipInfoMemory.getInstance().getById(info.getId());
        if (null == tipInfo) {
            return AjaxResult.errorResult("您修改的已不存在，请查证");
        }

        if (null == info.getName()) {
            info.setName(tipInfo.getName());
        }


        if (ValidateUtil.isNull(info.getName())) {
            return AjaxResult.errorResult("请输入类别名称");
        }


        //修改商品类别
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.TIP_INFO).append(" set ")
                .append(" name='").append(info.getName()).append("',note='").append(info.getNote())
                .append("',updateUser='").append(user.getUsername()).append("' ")
                .append(",descs='").append(info.getDescs()).append("',placeholder='").append(info.getPlaceholder()).append("'")
                .append(",note='").append(info.getNote())
                .append("',extra1='").append(ValidateUtil.isNotNull(info.getExtra1()) ? info.getExtra1() : "")
                .append("',extra2='").append(ValidateUtil.isNotNull(info.getExtra2()) ? info.getExtra2() : "")
                .append("',extra3='").append(ValidateUtil.isNotNull(info.getExtra3()) ? info.getExtra3() : "").append("'")
                .append(",code='").append(ValidateUtil.isNotNull(info.getCode()) ? info.getCode() : "").append("'")
                .append(" where id = ").append(info.getId()).append(" and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //修改缓存
        TipInfoMemory.getInstance().modify(info.getId());

        return AjaxResult.successResult();
    }


    //删除
    @RequestMapping(method = RequestMethod.POST, value = "/admin/tip/info/delete")
    @ResponseBody
    public String shop_label_delete(String token, Long id) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNotID(id)) {
            return AjaxResult.errorResult("请选择要删除的");
        }

        TipInfo tipInfo = TipInfoMemory.getInstance().getById(id);
        if (null == tipInfo) {
            return AjaxResult.errorResult("您要删除的已不存在");
        }

        //删除商品类别
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.TIP_INFO).append(" set delFlag = 1,updateUser='").append(user.getUsername())
                .append("' where id = ").append(id).append(" and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除失败，请稍后再试");
        }

        //在缓存中删除
        TipInfoMemory.getInstance().delete(id);

        return AjaxResult.successResult();
    }


    // 优齐同城便民信息的提示信息添加使用
    @RequestMapping(method = RequestMethod.POST, value = "/admin/tip/info/add/v2")
    @ResponseBody
    public String bianmin_tip_add(String token, TipInfo info, FileUploadInfo fileUploadInfo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (null == info) {
            return AjaxResult.errorResult("信息不完整，请填写完整");
        }
        if (StringUtils.isEmpty(info.getExtra1())) {
            return AjaxResult.errorResult("省不能为空");
        }
        if (StringUtils.isEmpty(info.getExtra2())) {
            return AjaxResult.errorResult("市不能为空");
        }
        if (StringUtils.isEmpty(info.getExtra3())) {
            return AjaxResult.errorResult("区不能为空");
        }

        long count = 0;
        StringBuilder sql = new StringBuilder();
        sql.append("select count(*) as counts from ").append(PojoTables.TIP_INFO).append(" where ")
                .append(" extra1 ='").append(info.getExtra1()).append("' and  ")
                .append(" extra2 ='").append(info.getExtra2()).append("' and  ")
                .append(" extra3 ='").append(info.getExtra3()).append("' and delFlag = 0")
                .append(" and tipType = ").append(info.getTipType());
        try {
            count = UserDaoSql.getInstance().getCount(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败,请稍后重试");
        }
        if (count > 0) {
            return AjaxResult.errorResult("当前" + info.getExtra1() + info.getExtra2() + info.getExtra3() + "已存在");
        }
        if (ValidateUtil.isNull(info.getName())) {
            return AjaxResult.errorResult("请输入名称");
        }
        if (null == info.getTipType()) {
            return AjaxResult.errorResult("类别不能为空");
        }
        if (fileUploadInfo != null && fileUploadInfo.getImage() != null) {
            String filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.NOTICE_IMAGE, fileUploadInfo.getImage());
            if (!ValidateUtil.isNull(filePath)) {
                if (ValidateUtil.isNotNetUrl(filePath)) {
                    info.setPlaceholder(SYS_CONFIG_PATH.IMAGE_BASE_URL + "/" + filePath);
                } else {
                    info.setPlaceholder(filePath);
                }
            }
        }
        if (info.getIsDefault() != null && info.getIsDefault() == 1) {
            try {
                cancelDefaultTip(info.getTipType());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("操作失败,请稍重试");
            }
        }
        if (info.getIsDefault() == null || info.getIsDefault() == 0) {
            info.setIsDefault(0);
        }
        long time = DateUtils.getCurrTime();
        info.setCreateTime(time);
        info.setDelFlag(0);
        info.setCreateUser(user.getUsername());
        //存入数据库
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.TIP_INFO, info);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("新增失败，请稍后再试");
        }
        //存入缓存
        TipInfoMemory.getInstance().add(time);
        return AjaxResult.successResult();
    }

    // 修改信息
    // 优齐同城便民信息的提示信息添加使用
    @RequestMapping(method = RequestMethod.POST, value = "/admin/tip/info/modify/v2")
    @ResponseBody
    public String bianmian_tip_modify(String token, TipInfo info, FileUploadInfo fileUploadInfo) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        if (info.getId() == null) {
            return AjaxResult.errorResult("id不能为空");
        }
        TipInfo dbTip = TipInfoMemory.getInstance().getById(info.getId());
        if (dbTip == null) {
            return AjaxResult.errorResult("提示信息不存在");
        }
        StringBuilder sql = new StringBuilder();
        sql.append(" update ").append(PojoTables.TIP_INFO).append(" set updateUser ='").append(user.getUsername()).append("'")
                .append("");

        if (info.getIsDefault() != null && info.getIsDefault() == 1) {
            if (dbTip.getIsDefault() != null && info.getIsDefault() == 1) {
            } else {
                // 取消原来的
                try {
                    cancelDefaultTip(dbTip.getTipType());
                } catch (SQLException e) {
                    e.printStackTrace();
                    return AjaxResult.errorResult("操作失败,请稍后重试");
                }
                sql.append(",isDefault =").append(info.getIsDefault()).append(" ");
            }
        } else if (info.getIsDefault() != null && info.getIsDefault() == 0) {
            sql.append(",isDefault = 0");
        }
        if (StringUtils.isNotEmpty(info.getNote())) {
            sql.append(",note ='").append(info.getNote()).append("'");
        }
        if (StringUtils.isNotEmpty(info.getName())) {
            sql.append(",name='").append(info.getName()).append("'");
        }
        if (StringUtils.isNotEmpty(info.getCode())) {
            sql.append(",code='").append(info.getCode()).append("'");
        }
        if (StringUtils.isNotEmpty(info.getDescs())) {
            sql.append(",descs='").append(info.getDescs()).append("'");
        }
        if (fileUploadInfo != null && fileUploadInfo.getImage() != null) {
            if (fileUploadInfo != null && fileUploadInfo.getImage() != null) {
                String filePath = JYImageUtils.saveImage(SYS_CONFIG_PATH.NOTICE_IMAGE, fileUploadInfo.getImage());
                if (!ValidateUtil.isNull(filePath)) {
                    if (ValidateUtil.isNotNetUrl(filePath)) {
                        sql.append(",placeholder = '").append(SYS_CONFIG_PATH.IMAGE_BASE_URL + "/" + filePath).append("' ");
                    } else {
                        sql.append(",placeholder = '").append(filePath).append("' ");
                    }
                }
            }
        }
        sql.append(" where delFlag = 0 and id = ").append(dbTip.getId());
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("操作失败,请稍后重试");
        }
        TipInfoMemory.getInstance().modify(info.getId());
        return AjaxResult.successResult();
    }

    // 获取便民信息提示信息
    @RequestMapping(method = RequestMethod.POST, value = "/tip/info/list/v2")
    @ResponseBody
    public String type_list(Integer tipType, String province, String city, String county, Integer page, Integer size) {
        if (page == null || page <= 0) {
            page = 1;
        }
        if (size == null || size <= 0) {
            size = 20;
        }
        List<TipInfo> list = TipInfoMemory.getInstance().listOfType(tipType);
        if (list == null || list.size() == 0) {
            return AjaxResult.successResult(0, 0, null);
        }
        List<TipInfo> resultList = new ArrayList<>();
        List<TipInfo> defaultList = new ArrayList<>();
        for (TipInfo tipInfo : list) {
            if (tipInfo == null) {
                continue;
            }
            if (StringUtils.isNotEmpty(tipInfo.getNote()) && tipInfo.getNote().equalsIgnoreCase("default")) {
                defaultList.add(tipInfo);
            }
            if (StringUtils.isNotEmpty(province)) {
                if (StringUtils.isNotEmpty(tipInfo.getExtra1()) && tipInfo.getExtra1().equalsIgnoreCase(province)) {
                } else {
                    continue;
                }
            }
            if (StringUtils.isNotEmpty(city)) {
                if (StringUtils.isNotEmpty(tipInfo.getExtra2()) && tipInfo.getExtra2().equalsIgnoreCase(city)) {
                } else {
                    continue;
                }
            }
            if (StringUtils.isNotEmpty(county)) {
                if (StringUtils.isNotEmpty(tipInfo.getExtra3()) && tipInfo.getExtra3().equalsIgnoreCase(county)) {
                } else {
                    continue;
                }
            }
            resultList.add(tipInfo);
        }
        if (resultList.size() > 0) {
            JYPageUtils.PageList pageList = JYPageUtils.getList(resultList, page, size);
            return AjaxResult.successResult(pageList.totalCount, pageList.size, pageList.list);
        } else {
            // 获取默认的
            if (defaultList.size() > 0) {
                return AjaxResult.successResult(defaultList.size(), defaultList.size(), defaultList);
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }

    // 取消默认的设置
    public void cancelDefaultTip(int tipType) throws SQLException {
        List<TipInfo> list = null;
        StringBuilder selSql = new StringBuilder();
        selSql.append("select * as counts from ").append(PojoTables.TIP_INFO)
                .append(" where delFlag =  0 and isDefault = 1 ").append(" and tipType = ").append(tipType);
        list = (List<TipInfo>) UserDaoSql.getInstance().list(TipInfo.class, selSql.toString());
        if (list != null && list.size() > 0) {
            HashSet<Long> set = new HashSet<>();
            for (TipInfo t : list) {
                set.add(t.getId());
            }
            // 更新
            StringBuilder updateSql = new StringBuilder();
            updateSql.append(" update ").append(PojoTables.TIP_INFO).append(" set isDefault =0 ")
                    .append(" where ").append("delFlag = 0 and id in (").append(StringUtils.join(set, ",")).append(")");
            UserDaoSql.getInstance().executeBySql(updateSql.toString());
            // 缓存
            for (Long id : set) {
                TipInfoMemory.getInstance().modify(id);
            }
        }
    }

    private List<TipInfoVO> conventTOVOList(List<TipInfo> list) {
        if (!ValidateUtil.isAbsList(list)) {
            return null;
        }
        List<TipInfoVO> voList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (null == list.get(i)) {
                continue;
            }
            TipInfoVO vo = new TipInfoVO();
            BeanUtils.copyProperties(list.get(i), vo);
            voList.add(vo);
        }
        return voList;
    }

}
